package xyz.linyuxb.utils;

import cn.hutool.core.map.MapUtil;
import org.apache.commons.collections4.SetUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.*;

/**
 * @Author: linyuxb
 * @Date: 2021/11/15 10:46 上午
 * @Desc: 主函数逻辑
 */
public abstract class LyMain {
    private static final String PACKAGE_NAME = "xyz.linyuxb.script";
    private static final Set<String> EVA = SetUtils.hashSet("local", "test", "prod");

    /**
     * 逻辑执行
     */
    public void run() {
        try {
            System.out.println("JobMain 你好...");
            System.out.println("参数描述：exit 结束服务");
            Scanner scanner = new Scanner(System.in);
            System.out.println("请指定环境：local、test、prod");
            System.out.print("> ");
            String eva = scanner.nextLine();
            while (!EVA.contains(eva)) {
                System.out.println("环境输入错误，请重新输入");
                System.out.print("> ");
                eva = scanner.nextLine();
            }
            System.out.println("选中环境：" + eva);
            Properties load = ResourceLoad.load(eva);
            // 获取包名下所有类
            Set<Class<?>> classes = ClassUtil.getClasses(PACKAGE_NAME);
            Map<String, Class<?>> classMap = MapUtil.newHashMap();
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("可执行服务有：");
            for (Class c : classes) {
                String name = c.getCanonicalName().replace(PACKAGE_NAME + ".", StringUtils.EMPTY);
                stringBuilder.append(name + StringUtils.SPACE);
                classMap.put(name, c);
            }
            System.out.println(stringBuilder);
            System.out.println("请输入命令：");
            while (true) {
                System.out.print("> ");
                String str = scanner.nextLine();
                if ("exit".equalsIgnoreCase(str)) {
                    break;
                }
                Class<?> aClass = classMap.get(str);
                if (Objects.isNull(aClass)) {
                    System.out.println("亲，您输入服务名称不匹配，请重新输入：");
                    continue;
                }
                BaseScript script = (BaseScript) aClass.newInstance();
                script.doScript(load);
                System.out.println("任务执行完成：" + str);
                System.out.println("请出入下一条命令：");
            }
            System.out.println("JobMain 拜拜...");
        } catch (Exception e) {
            System.out.println("JobMain 哎呀 出异常了...");
            System.err.println(e);
            e.printStackTrace();
        }
    }
}
